package Servlets;

import main.ServerGlobals;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import protocol.HTTPRequest;
import protocol.HTTPResponse;
import protocol.Headers;
import SQL.SQLLiteHandler;

public class create_Group extends Servlet {

	private boolean isERROR_929(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		JSONObject msgArgs = httpRequest.getfHttpmsg().toJSONObject();
		String[] users = msgArgs.get("Users").toString().split(",");
		JSONArray userSearch = this.getUserSearch(httpRequest, serverGlobals);
		if (userSearch.size() < users.length) {
			return true;

		}
		return false;
	}

	private JSONArray getUserSearch(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		JSONObject msgArgs = httpRequest.getfHttpmsg().toJSONObject();
		String[] users = msgArgs.get("Users").toString().split(",");
		String toUse = new String("'");
		for (int i = 0; i < users.length; i++) {
			toUse += SQLLiteHandler.clean(users[i]) + "','";
		}
		toUse = toUse.substring(0, toUse.length() - 2);

		JSONArray userSearch = this.fSQLLiteHandler.Query("select * from "
				+ WhatsAppConstatnts.TABLE_USERS + " where "
				+ WhatsAppConstatnts.USERNAME + " in (" + toUse + ")");
		return userSearch;
	}

	private HTTPResponse getUnknownUsersResponse(String[] usersSubmitted,
			JSONArray SQLResult) {
		String res = new String();
		for (int j = 0; j < usersSubmitted.length; j++) {
			boolean found = false;
			for (int i = 0; i < SQLResult.size(); i++) {

				if (((JSONObject) SQLResult.get(i))
						.get(WhatsAppConstatnts.USERNAME).toString()
						.equals(usersSubmitted[j])) {
					found = true;
				}
			}
			if (!found) {
				res += WhatsAppConstatnts.ERROR_929 + usersSubmitted[j] + "\n";
			}
		}
		return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
				new JSONObject(), res, false);
	}

	private boolean isGroupAvailable(String groupName) {
		JSONArray groupAvailable = this.fSQLLiteHandler.Query("select * from "
				+ WhatsAppConstatnts.TABLE_GROUPS + " where "
				+ WhatsAppConstatnts.GROUP_NAME + "='"
				+ SQLLiteHandler.clean(groupName).toString() + "'");
		if (groupAvailable.size() > 0) {
			return false;
		}
		return true;
	}

	private boolean createGroup(String GroupName) {
		try {
			this.fSQLLiteHandler
					.Query("INSERT INTO GroupNames (GroupName) values ('"
							+ SQLLiteHandler.clean(GroupName) + "')");
			return true;
		} catch (RuntimeException e) {
			if (e.getMessage().equals(SQLLiteHandler.SQL_CONCURRENCY)) {
				return false;
			}
			return true;
		}
	}

	private void addUsers(String[] userNames, String GroupName) {
		for (int i = 0; i < userNames.length; i++) {
			JSONArray phoneAsJSON = this.fSQLLiteHandler.Query("select "
					+ WhatsAppConstatnts.PHONE + " from "
					+ WhatsAppConstatnts.TABLE_USERS + " where "
					+ WhatsAppConstatnts.USERNAME + "='"
					+ SQLLiteHandler.clean(userNames[i]) + "'");
			String phone = ((JSONObject) phoneAsJSON.get(0)).get(
					WhatsAppConstatnts.PHONE).toString();
			this.fSQLLiteHandler.Query("Insert into "
					+ WhatsAppConstatnts.TABLE_GROUPS + " ("
					+ WhatsAppConstatnts.GROUP_NAME + ","
					+ WhatsAppConstatnts.USERNAME + ","
					+ WhatsAppConstatnts.PHONE + ") values ('"
					+ SQLLiteHandler.clean(GroupName) + "','"
					+ SQLLiteHandler.clean(userNames[i]) + "','"
					+ SQLLiteHandler.clean(phone) + "')");
		}
	}

	@Override
	public HTTPResponse process(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		if (!this.isCorrectMethod(httpRequest, Headers.POST)) {
			return new HTTPResponse(Headers.STATUS_405, Headers.HTTP_VERSION,
					new JSONObject(), "", false);
		}
		if (!this.isAuthorized(httpRequest, serverGlobals)) {
			return new HTTPResponse(Headers.STATUS_403, Headers.HTTP_VERSION,
					new JSONObject(), "", false);
		}
		if (!this.areParametersRequiredSent(new String[] { "Users",
				WhatsAppConstatnts.GROUP_NAME }, httpRequest)) {
			return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
					new JSONObject(), WhatsAppConstatnts.ERROR_675, false);
		}
		JSONObject msgArgs = httpRequest.getfHttpmsg().toJSONObject();
		String[] users = msgArgs.get("Users").toString().split(",");

		if (this.isERROR_929(httpRequest, serverGlobals)) {
			return getUnknownUsersResponse(users,
					this.getUserSearch(httpRequest, serverGlobals));
		}

		if (!isGroupAvailable(msgArgs.get(WhatsAppConstatnts.GROUP_NAME)
				.toString())
				|| (!createGroup(msgArgs.get(WhatsAppConstatnts.GROUP_NAME)
						.toString()))) {
			return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
					new JSONObject(), WhatsAppConstatnts.ERROR_511, false);
		}

		addUsers(users, msgArgs.get(WhatsAppConstatnts.GROUP_NAME).toString());
		return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
				new JSONObject(), "Group "
						+ msgArgs.get(WhatsAppConstatnts.GROUP_NAME).toString()
						+ " Created", false);

	}
}
